package com.ler.yrmall.ware.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ler.yrmall.enums.BasicStatusEnum;
import com.ler.yrmall.enums.ErrorCodeEnum;
import com.ler.yrmall.exception.BusinessException;
import com.ler.yrmall.ware.entity.WareEntity;
import com.ler.yrmall.ware.entity.WareSkuEntity;
import com.ler.yrmall.ware.mapper.WareInfoMapper;
import com.ler.yrmall.ware.service.WareService;
import com.ler.yrmall.basic.Form;
import com.ler.yrmall.ware.service.WareSkuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author leron
 */
@Service
public class WareServiceImpl extends ServiceImpl<WareInfoMapper, WareEntity> implements WareService {

    @Resource
    private WareSkuService wareSkuService;

    @Override
    public IPage<WareEntity> find(Form request) {
        return this.page(request.getPage(), Wrappers.<WareEntity>lambdaQuery()
                .like(request.getKeyword() != null,WareEntity::getName,request.getKeyword()).orderByAsc(WareEntity::getSort)
                .orderByDesc(WareEntity::getCreateTime));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteWare(List<Long> ids) {
        List<WareSkuEntity> list = wareSkuService.list(Wrappers.<WareSkuEntity>lambdaQuery().eq(WareSkuEntity::getWareId, ids));
        if (!list.isEmpty()) {
            throw new BusinessException(ErrorCodeEnum.WARE_USED);
        }
        List<WareEntity> wareList = this.listByIds(ids)
                .stream()
                .filter(item -> BasicStatusEnum.SystemEnableStatus.ENABLED.getCode().equals(item.getStatus()))
                .collect(Collectors.toList());
        if (!wareList.isEmpty()) {
            throw new BusinessException(ErrorCodeEnum.WARE_USED);
        }
        this.removeByIds(ids);
    }
}